package com.lzk.basic.controller;

import com.lzk.basic.util.FastDfsUtils;
import com.lzk.basic.util.JsonResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    /**
     * fastDfs文件上传
     * @param file
     * @return
     */
    @PostMapping
    public JsonResult upload(@RequestPart(value="file",required = true) MultipartFile file){
        try {
            String originalFilename = file.getOriginalFilename();
            //取出文件名字的后缀名，不含有.
            String exName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
            //上传到fastDfs服务器的路径
            String filePath = FastDfsUtils.upload(file.getBytes(), exName);
            //将上传路径返回到前端
            return JsonResult.me().setResultObj(filePath);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me(false,"上传失败!"+e.getMessage());
        }
    }


    @DeleteMapping
    public JsonResult del(@RequestParam(value = "path",required = true) String path  ){
        try {
            //取出路径第一个/
            String pathTmp = path.substring(1);
            //取出组名
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/"));
            //取出文件路径名
            String filePath = pathTmp.substring(pathTmp.indexOf("/")+1);
            //执行删除
            FastDfsUtils.delete(groupName,filePath);
            return JsonResult.me();
        } catch (Exception e) {
           e.printStackTrace();
           return JsonResult.me(false,"删除失败！"+e.getMessage());
        }
    }
}
